//
//  WelcomeViewController.m
//  SecretRoom
//
//  Created by Sitdhibhong Laokok on 9/2/54 BE.
//  Copyright 2554 App Tree. All rights reserved.
//

#import "WelcomeViewController.h"

#import "DailyProgressViewController.h"

@interface WelcomeViewController ()
- (void)authenticateWithSecretRoom;
- (void)rampUpAuthentication;
- (void)tearDownAuthentication:(NSDictionary *)userMessage;
- (void)saveUserCredentialWhileAuthorized:(NSDictionary *)userCredentials;
@end

@implementation WelcomeViewController

@synthesize username;
@synthesize password;
@synthesize usernameField;
@synthesize passwordField;
@synthesize context;

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (id)initWithManagedObjectContext:(NSManagedObjectContext *)cx
{
    if (self = [super initWithStyle:UITableViewStyleGrouped]) {
        self.context = cx;
    }
    
    return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.title = @"Secret Room";
    
    self.username = [[NSUserDefaults standardUserDefaults] objectForKey:kSRPreferenceRemoteValueUsername];
    self.password = [[NSUserDefaults standardUserDefaults] objectForKey:kSRPreferenceRemoteValuePassword];
    
    NSLog(@"Username: %@", [[NSUserDefaults standardUserDefaults] objectForKey:kSRPreferenceRemoteValueUsername]);
    NSLog(@"Password: %@", [[NSUserDefaults standardUserDefaults] objectForKey:kSRPreferenceRemoteValuePassword]);
    
    if ([self.username length] > 0 && [self.password length] > 0) {
        [self authenticateWithSecretRoom];
    }
    
    CGRect fieldRect = CGRectMake(150, 44 - 32, 150, 32);
    
    UITextField *uname = [[UITextField alloc] initWithFrame:fieldRect];
    uname.autoresizingMask = (UIViewAutoresizingFlexibleHeight|UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleLeftMargin);
    uname.delegate = self;
    uname.placeholder = @"Username";
    uname.tag = 1;
    self.usernameField = uname;
    [uname release];
    
    UITextField *pwd = [[UITextField alloc] initWithFrame:fieldRect];
    pwd.autoresizingMask = self.usernameField.autoresizingMask;
    pwd.secureTextEntry = YES;
    pwd.delegate = self;
    pwd.placeholder = @"Password";
    pwd.tag = 2;
    self.passwordField = pwd;
    [pwd release];
    
    activityIndicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    activityIndicator.hidesWhenStopped = YES;
    activityIndicator.center = CGPointMake([UIScreen mainScreen].bounds.size.width * 0.5, [UIScreen mainScreen].bounds.size.height * 0.6);
    
    self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc] initWithTitle:@"Sign Up" 
                                                                               style:UIBarButtonItemStyleBordered 
                                                                              target:self 
                                                                              action:@selector(signUpButtonClicked:)] autorelease];
    
    
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
    
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    usernameField.text = @"";
    passwordField.text = @"";
    
    [usernameField becomeFirstResponder];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return section ? 1 : 2 ;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    } else {
        id textField = [cell viewWithTag:1];
        if (textField != nil) {
            [textField removeFromSuperview];
        } else {
            textField = [cell viewWithTag:2];
            if (textField != nil) {
                [textField removeFromSuperview];
            }
        }
    }
    
    // Configure the cell...
    
    if (indexPath.section) {
        cell.textLabel.text = @"Sign In";
        cell.textLabel.textAlignment = UITextAlignmentCenter;
    } else {
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        if (indexPath.row) {
            cell.textLabel.text = @"Password";
            [cell addSubview:passwordField];
        } else {
            cell.textLabel.text = @"Username";
            [cell addSubview:usernameField];
        }

    }
    
    return cell;
}


#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (!indexPath.section) return;
    
    [tableView cellForRowAtIndexPath:indexPath].selected = NO;
    [self authenticateWithSecretRoom];
}

#pragma mark - UITextField
- (void)textFieldDidEndEditing:(UITextField *)textField
{
    if (textField.tag == 1) {
        self.username = textField.text;
    } else if (textField.tag == 2) {
        self.password = textField.text;
    }
}

#pragma mark - dealloc
- (void)dealloc {
    [activityIndicator release];
    
    [username release];
    [password release];
    
    [usernameField release];
    [passwordField release];
    
    [context release];
    
    [super dealloc];
}

#pragma mark - Custom method defined
- (IBAction)signUpButtonClicked:(id)sender 
{
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:kSRRemoteInformationSecretRoomRegisterURL]];
}

- (void)rampUpAuthentication
{
    [activityIndicator startAnimating];
    [usernameField setEnabled:NO];
    [passwordField setEnabled:NO];
}

- (void)tearDownAuthentication:(NSDictionary *)userMessage
{
    [activityIndicator stopAnimating];
    [usernameField setEnabled:YES];
    [passwordField setEnabled:YES];
    [self.usernameField becomeFirstResponder];
    
    if (userMessage != nil) {
//        NSDictionary *userMessage = [[userInfo userInfo] objectForKey:@"userInfo"];
        if ([userMessage objectForKey:@"error"] != nil) {
            NSLog(@"%s %i", __PRETTY_FUNCTION__, __LINE__);
            UIAlertView *alertMessage = [[UIAlertView alloc] initWithTitle:@"Secret Room" 
                                                                   message:[userMessage objectForKey:@"error"] 
                                                                  delegate:nil 
                                                         cancelButtonTitle:@"OK" 
                                                         otherButtonTitles:nil];
            
            [alertMessage show];
            [alertMessage release];
        } else {
            NSLog(@"%s, %i", __PRETTY_FUNCTION__, __LINE__);
            NSLog(@"Message from user Info %@", userMessage);
            
            if ([userMessage count] > 2) {
                [self saveUserCredentialWhileAuthorized:userMessage];
            }
            
            [self.parentViewController dismissModalViewControllerAnimated:YES];
            
            DailyProgressViewController *dpc = [[DailyProgressViewController alloc] initWithManagedObjectContext:self.context];
            UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:dpc];
            [self.parentViewController presentModalViewController:nav animated:NO];
            
            [dpc release];
            [nav release];
        }
    } else {
        NSLog(@"%s %i: UserInfo is nil", __PRETTY_FUNCTION__, __LINE__);
    }
    
}

- (void)saveUserCredentialWhileAuthorized:(NSDictionary *)userCredentials
{
    NSLog(@"%s %i", __PRETTY_FUNCTION__, __LINE__);
    [[NSNotificationCenter defaultCenter] postNotificationName:kSRNotificationCenterNameUserAuthenticationCredentialSave 
                                                        object:nil 
                                                      userInfo:[NSDictionary dictionaryWithObject:userCredentials forKey:@"userInfo"]];
}

- (void)authenticateWithSecretRoom
{
    [self rampUpAuthentication];
    
    NSMutableDictionary *userInfomation = nil;
    
    NSLog(@"%s %i : username = %@, password = %@", __PRETTY_FUNCTION__, __LINE__, self.username, self.password);
    
    if ([self.username length] > 0 && [self.password length] > 0) {
        NSError *error = nil;
        userInfomation = [[NSMutableDictionary dictionaryWithDictionary:[[SRConnectionControlCenter sharedInstance] authenticationToSecretRoomWithUsername:self.username password:self.password error:&error]] retain];

        [userInfomation setObject:username forKey:@"remote_username"];
        [userInfomation setObject:password forKey:@"remote_password"];
        
    } else {
        UIAlertView *credentialRequire = [[UIAlertView alloc] initWithTitle:@"Warning!!!" message:@"Username and Password are both required" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
        
        [credentialRequire show];
        [credentialRequire release];
    }
    
    [self tearDownAuthentication:userInfomation];
    
    if (userInfomation != nil) {
        [userInfomation release];
    }

}
@end
